const Sequelize = require('sequelize')
const config = require('../config')
const sequelize = new Sequelize(
  'belongsToMany',
  config.dbUser,
  config.dbPassword,
  {
    host: config.dbHost,
    port: config.dbPort,
    dialect: 'mysql',
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000
    },
    timezone: '+08:00',
    // 请参考 Querying - 查询 操作符 章节
    operatorsAliases: false
  }
)

sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.')
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err)
  })
const User = sequelize.define(
  'user',
  {
    name: Sequelize.STRING
  }
)
const Project = sequelize.define('project', {
  title: Sequelize.STRING,
  users: Sequelize.STRING
})
const UserProjects = sequelize.define('userProjects', {
  userId: Sequelize.INTEGER,
  projectId: Sequelize.INTEGER
})

User.belongsToMany(Project, { through: UserProjects, as: 'UserProjects' })
Project.belongsToMany(User, { through: UserProjects, as: 'UserProjects' })
// 也能用于 `hasOne`
sequelize.sync({ force: false }).then(() => {
  // Promise.all([
  //   Project.create({title: 'projrct' + new Date()}),
  //   User.findAll({
  //     where: {
  //       id: [6, 2]
  //     }
  //   })
  // ]).then((results) => {
  //   results[0].setUserProjects(results[1])
  // })

  Project.findOne({
    where: { id: 14 }
  }).then(projrcts => {
    projrcts.getUserProjects().then(res => {
      console.log(res)
    })
  })
})
